﻿using MediatR; 
using PublicClass;
using S.Organization.Domian.Model;
using S.Organization.Infrastructure;
using S.Organization.Read.API.Application.Command.ClientCommand;
using S.Organization.Read.API.Application.Command.SupplierCommand;

namespace S.Organization.Read.API.Application.CommandHandler.ClientCommandHandler
{
    public class GetClientCommandHandler : IRequestHandler<GetClientCommand, PageInfo<Client>>
    {
        private readonly IBaseRepository<Client> _repository;


        public GetClientCommandHandler(IBaseRepository<Client> repository)
        {
            _repository = repository;
        }

        public async Task<PageInfo<Client>> Handle(GetClientCommand request, CancellationToken cancellationToken)
        {
            // request.SupplierNumber=DateTime.Now.ToString();
            var query = await _repository.AllAsync();

            PageInfo<Client> list = new PageInfo<Client>();

            //数据总条数
            list.totalCount = query.Count();

            //总页数
            list.pageCount = (int)Math.Ceiling(list.totalCount * 1.0 / (request.Size));

            //编号查询
            if (!string.IsNullOrEmpty(request.ClientNumber))
            {
                query = query.Where(x => x.ClientNumber == request.ClientNumber);
            }

            //名称查询
            if (!string.IsNullOrEmpty(request.ClientName))
            {
                query = query.Where(x => x.ClientName.Contains(request.ClientName));
            }

            //负责人电话 
            if (!string.IsNullOrEmpty(request.PrincipalTel))
            {
                query = query.Where(x => x.PrincipalTel == request.PrincipalTel);
            }

            // 所属市场
            if (!string.IsNullOrEmpty(request.Market))
            {
                query = query.Where(x => x.Market == request.Market);
            }

            // 服务人员
            if (!string.IsNullOrEmpty(request.ServiceStaff))
            {
                query = query.Where(x => x.ServiceStaff == request.ServiceStaff);
            }

            // 归集档案
            if (!string.IsNullOrEmpty(request.CollectionFile))
            {
                query = query.Where(x => x.CollectionFile == request.CollectionFile);
            }

            // 使用状态
            if (request.UseOftate != null)
            {
                query = query.Where(x => x.UseOftate == request.UseOftate);
            }
            query = query.OrderByDescending(x => x.ClientId);
            list.datas = query.Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();
            return list;
        }
    }
}
